﻿namespace ContactsSync.Providers
{
    using System;
    using System.Windows;
    using ContactsSync.Infrastructure;
    using ContactsSync.Providers.ViewModels;
    using Microsoft.Practices.Composite.Modularity;
    using Microsoft.Practices.Composite.Regions;
    using Microsoft.Practices.Unity;

    public abstract class BaseProviderModule : IModule
    {
        private readonly IRegionManager regionManager;

        protected BaseProviderModule(IUnityContainer container, IRegionManager regionManager)
        {
            this.Container = container;
            this.regionManager = regionManager;
        }

        protected IUnityContainer Container { get; private set; }

        public void Initialize()
        {
            InitializeResourceDictionary();
            
            IContactsProvider contactsProvider = this.RetrieveContactsProvider();

            ProviderViewModel providerViewModel = this.Container.Resolve<ProviderViewModel>();
            providerViewModel.SetProvider(contactsProvider);

            this.regionManager.Regions[Regions.ProvidersRegion].Add(providerViewModel);
        }

        public abstract IContactsProvider RetrieveContactsProvider();

        private static void InitializeResourceDictionary()
        {
            ResourceDictionary dictionary = new ResourceDictionary();
            dictionary.Source = new Uri("ContactsSync.Providers;component/Resources/ProvidersResourceDictionary.xaml", UriKind.Relative);

            Application.Current.Resources.MergedDictionaries.Add(dictionary);
        }
    }
}
